#Xray工具条函数脚本

from universal.common_header import *
from universal.common_header_widget import *
from Module.xRayDetection.xray.logs import Logger
from Module.xRayDetection.ftp_function import TextBrowserNews

name_class_dir_list = []
class XrayClass:
    def __init__(self, parent=None):
        self.mainwindow = parent
        self.actions = self.mainwindow.actions
        self.logger = init_log()
        self.canvas = self.mainwindow.canvas
        self.TextBrowser = self.mainwindow.TextBrowser
        self.Ftp = None
        self.list_Path = []

    def SHOW_Label(self, projdir, jpgbaseName, class_name, num):
        path = os.path.join(projdir, class_name) + os.sep + jpgbaseName
        if os.path.exists(path):
            self.Pic_Label(num)

    def PanDuan(self,unicodeFilePath,xmlFilePath):#判断是否存在过漏杀文件
        self.init_Label()
        jpgbaseName = os.path.basename(unicodeFilePath)
        projdir = os.path.dirname(xmlFilePath)

        # self.SHOW_Label(projdir, jpgbaseName, '过杀', 0)
        self.SHOW_Label(projdir, jpgbaseName, 'OK', 0)
        self.SHOW_Label(projdir, jpgbaseName, '正极翻', 1)
        self.SHOW_Label(projdir, jpgbaseName, '负极翻', 2)
        self.SHOW_Label(projdir, jpgbaseName, '机损', 3)
        self.SHOW_Label(projdir, jpgbaseName, '超限', 4)
        self.SHOW_Label(projdir, jpgbaseName, '错层', 5)
        self.SHOW_Label(projdir, jpgbaseName, '极片偏移', 6)
        self.SHOW_Label(projdir, jpgbaseName, '局部偏移', 7)
        self.SHOW_Label(projdir, jpgbaseName, '整体偏移', 8)
        # self.SHOW_Label(projdir, jpgbaseName, '漏杀', 9)
        self.SHOW_Label(projdir, jpgbaseName, 'NG', 9)

    def init_Label(self):
        self.actions.Over_kill.setEnabled(True)
        self.actions.Escape_kill.setEnabled(True)
        self.actions.PosetiveEscape_kill.setEnabled(True)
        self.actions.NegativeEscape_kill.setEnabled(True)
        self.actions.xray_class1.setEnabled(True)
        self.actions.xray_class2.setEnabled(True)
        self.actions.xray_class3.setEnabled(True)
        self.actions.xray_class4.setEnabled(True)
        self.actions.xray_class5.setEnabled(True)
        self.actions.xray_class6.setEnabled(True)

        self.canvas.lab2.hide()
        self.canvas.lab3.hide()
        self.canvas.lab4.hide()
        self.canvas.xray_class1.hide()
        self.canvas.xray_class2.hide()
        self.canvas.xray_class3.hide()
        self.canvas.xray_class4.hide()
        self.canvas.xray_class5.hide()
        self.canvas.xray_class6.hide()
        self.canvas.Escape_kill.hide()

    def Pic_Label(self,num):
        self.init_Label()
        if num == 0:
            self.actions.Over_kill.setEnabled(False)
            self.canvas.lab2.show()
        if num == 1:
            self.actions.PosetiveEscape_kill.setEnabled(False)
            self.canvas.lab3.show()
        if num == 2:
            self.actions.NegativeEscape_kill.setEnabled(False)
            self.canvas.lab4.show()
        if num == 3:
            self.actions.xray_class1.setEnabled(False)
            self.canvas.xray_class1.show()
        if num == 4:
            self.actions.xray_class2.setEnabled(False)
            self.canvas.xray_class2.show()
        if num == 5:
            self.actions.xray_class3.setEnabled(False)
            self.canvas.xray_class3.show()
        if num == 6:
            self.actions.xray_class4.setEnabled(False)
            self.canvas.xray_class4.show()
        if num == 7:
            self.actions.xray_class5.setEnabled(False)
            self.canvas.xray_class5.show()
        if num == 8:
            self.actions.xray_class6.setEnabled(False)
            self.canvas.xray_class6.show()
        if num == 9:
            self.actions.Escape_kill.setEnabled(False)
            self.canvas.Escape_kill.show()

    def Delete_file(self, pathdir, jpgbaseName, xmlbaseName):
        pic = pathdir + os.sep + jpgbaseName
        self.Remove_file(pic)
        if xmlbaseName:
            xml = pathdir + os.sep + xmlbaseName
            self.Remove_file(xml)

    def Remove_file(self,path):
        if os.path.exists(path):
            os.remove(path)

    def Copy_file(self,path,dir):
        if os.path.exists(path):
            copy(path, dir)

    def Xray_Class(self,defaultSaveDir,filePath,xmlFilePath,class_name,main=None,sub=None):
        """
        defaultSaveDir：图像路径文件夹
        filePath：图像绝对路径
        xmlFilePath：工程文件路径
        savedFileName：图像绝对路径（不含后缀）
        jpgbaseName：图像名字 （***.jpg）
        projdir：工程文件夹路径
        """
        try:
            if defaultSaveDir is not None and len(ustr(defaultSaveDir)):
                if filePath:
                    savedFileName = os.path.splitext(filePath)[0]
                    jpgbaseName = os.path.basename(filePath)
                    projdir = os.path.dirname(xmlFilePath)

                    name_class_dir = os.path.join(projdir,'ClassImg', class_name)
                    name_class_dir_list.append(name_class_dir)

                    OverkillDir = os.path.join(projdir, 'OK') #过杀路径
                    PoseEscapeDir = os.path.join(projdir, '正极翻')
                    NegaEscapeDir = os.path.join(projdir, '负极翻')
                    Class1Dir = os.path.join(projdir, '机损')
                    Class2Dir = os.path.join(projdir, '超限')
                    Class3Dir = os.path.join(projdir, '错层')
                    Class4Dir = os.path.join(projdir, '极片偏移')
                    Class5Dir = os.path.join(projdir, '局部偏移')
                    Class6Dir = os.path.join(projdir, '整体偏移')
                    EscapekillDir = os.path.join(projdir, 'NG')

                    Class_All = [OverkillDir,PoseEscapeDir,NegaEscapeDir,Class1Dir,
                                 Class2Dir,Class3Dir,Class4Dir,Class5Dir,Class6Dir,EscapekillDir]

                    if class_name == 'OK':
                        self.overkill(filePath,savedFileName, jpgbaseName, Class_All)
                    elif class_name == '正极翻':
                        self.PosetiveEscape_kill(filePath,savedFileName, jpgbaseName, Class_All)
                    elif class_name == '负极翻':
                        self.NegativeEscape_kill(filePath, savedFileName, jpgbaseName, Class_All)
                    elif class_name == '机损':
                        self.class_1(filePath, savedFileName, jpgbaseName, Class_All)
                    elif class_name == '超限':
                        self.class_2(filePath, savedFileName, jpgbaseName, Class_All)
                    elif class_name == '错层':
                        self.class_3(filePath, savedFileName, jpgbaseName, Class_All)
                    elif class_name == '极片偏移':
                        self.class_4(filePath, savedFileName, jpgbaseName, Class_All)
                    elif class_name == '局部偏移':
                        self.class_5(filePath, savedFileName, jpgbaseName, Class_All)
                    elif class_name == '整体偏移':
                        self.class_6(filePath, savedFileName, jpgbaseName, Class_All)
                    elif class_name == 'NG':
                        self.escapekill(filePath, savedFileName, jpgbaseName, Class_All)
                    elif class_name == '撤销标签类别':
                        self.DeleteEveryKill(savedFileName, jpgbaseName, Class_All)
                    elif class_name == '上传':
                        self.UpLoad(Class_All,defaultSaveDir,main,sub)
                    else:
                        self.classImg(filePath, savedFileName, jpgbaseName,name_class_dir)

        except Exception as e:
            self.logger.log(Logger.ERROR, str(e), exception=True)
            TextBrowserNews(self.TextBrowser,news=e)

    def overkill(self,filePath,savedFileName,jpgbaseName,Class_All):
        # -------------图标部分------------
        self.Pic_Label(0)
        # -------------把文件移动到文件夹---------------
        OverkillDir = Class_All[0]
        MK_dir(OverkillDir)  #创建过杀文件夹
        copy(filePath, OverkillDir) #将图像复制过去、
        xmlfile = savedFileName + '.xml'
        xmlbaseName = os.path.basename(xmlfile)   #判断有XML文件的话也一起复制过去
        self.Copy_file(xmlfile,OverkillDir)


        #------------判断别的文件夹有没有这张照片和标签，有的话就删除--------------------
        for i in range(len(Class_All)):
            if i != 0:
                if os.path.exists(Class_All[i]):
                    self.Delete_file(Class_All[i], jpgbaseName, xmlbaseName)

    def PosetiveEscape_kill(self,filePath,savedFileName,jpgbaseName,Class_All):
        # -------------图标部分------------
        self.Pic_Label(1)
        # -------------把文件移动到文件夹---------------
        PoseEscapeDir = Class_All[1]
        MK_dir(PoseEscapeDir)  # 创建过杀文件夹
        copy(filePath, PoseEscapeDir)  # 将图像复制过去、
        xmlfile = savedFileName + '.xml'
        xmlbaseName = os.path.basename(xmlfile)  # 判断有XML文件的话也一起复制过去
        # self.Copy_file(xmlfile, PoseEscapeDir)

        # ------------判断别的文件夹有没有这张照片和标签，有的话就删除--------------------
        for i in range(len(Class_All)):
            if i != 1:
                if os.path.exists(Class_All[i]):
                    self.Delete_file(Class_All[i], jpgbaseName, xmlbaseName)

    def NegativeEscape_kill(self,filePath,savedFileName,jpgbaseName,Class_All):
        # -------------图标部分------------
        self.Pic_Label(2)
        # -------------把文件移动到文件夹---------------
        NegaEscapeDir = Class_All[2]
        MK_dir(NegaEscapeDir)  # 创建过杀文件夹
        copy(filePath, NegaEscapeDir)  # 将图像复制过去、
        xmlfile = savedFileName + '.xml'
        xmlbaseName = os.path.basename(xmlfile)  # 判断有XML文件的话也一起复制过去
        # self.Copy_file(xmlfile, NegaEscapeDir)

        # ------------判断别的文件夹有没有这张照片和标签，有的话就删除--------------------
        for i in range(len(Class_All)):
            if i != 2:
                if os.path.exists(Class_All[i]):
                    self.Delete_file(Class_All[i], jpgbaseName, xmlbaseName)

    def class_1(self,filePath,savedFileName,jpgbaseName,Class_All):
        # -------------图标部分------------
        self.Pic_Label(3)
        # -------------把文件移动到文件夹---------------
        Class1Dir = Class_All[3]
        MK_dir(Class1Dir)  # 创建过杀文件夹
        copy(filePath, Class1Dir)  # 将图像复制过去、
        xmlfile = savedFileName + '.xml'
        xmlbaseName = os.path.basename(xmlfile)  # 判断有XML文件的话也一起复制过去
        # self.Copy_file(xmlfile, Class1Dir)

        # ------------判断别的文件夹有没有这张照片和标签，有的话就删除--------------------
        for i in range(len(Class_All)):
            if i != 3:
                if os.path.exists(Class_All[i]):
                    self.Delete_file(Class_All[i], jpgbaseName, xmlbaseName)

    def class_2(self,filePath,savedFileName,jpgbaseName,Class_All):
        # -------------图标部分------------
        self.Pic_Label(4)
        # -------------把文件移动到文件夹---------------
        Class2Dir = Class_All[4]
        MK_dir(Class2Dir)  # 创建过杀文件夹
        copy(filePath, Class2Dir)  # 将图像复制过去、
        xmlfile = savedFileName + '.xml'
        xmlbaseName = os.path.basename(xmlfile)  # 判断有XML文件的话也一起复制过去
        # self.Copy_file(xmlfile, Class2Dir)

        # ------------判断别的文件夹有没有这张照片和标签，有的话就删除--------------------
        for i in range(len(Class_All)):
            if i != 4:
                if os.path.exists(Class_All[i]):
                    self.Delete_file(Class_All[i], jpgbaseName, xmlbaseName)

    def class_3(self,filePath,savedFileName,jpgbaseName,Class_All):
        # -------------图标部分------------
        self.Pic_Label(5)
        # -------------把文件移动到文件夹---------------
        Class3Dir = Class_All[5]
        MK_dir(Class3Dir)  # 创建过杀文件夹
        copy(filePath, Class3Dir)  # 将图像复制过去、
        xmlfile = savedFileName + '.xml'
        xmlbaseName = os.path.basename(xmlfile)  # 判断有XML文件的话也一起复制过去
        # self.Copy_file(xmlfile, Class3Dir)

        # ------------判断别的文件夹有没有这张照片和标签，有的话就删除--------------------
        for i in range(len(Class_All)):
            if i != 5:
                if os.path.exists(Class_All[i]):
                    self.Delete_file(Class_All[i], jpgbaseName, xmlbaseName)

    def class_4(self,filePath,savedFileName,jpgbaseName,Class_All):
        # -------------图标部分------------
        self.Pic_Label(6)
        # -------------把文件移动到文件夹---------------
        Class4Dir = Class_All[6]
        MK_dir(Class4Dir)  # 创建过杀文件夹
        copy(filePath, Class4Dir)  # 将图像复制过去、
        xmlfile = savedFileName + '.xml'
        xmlbaseName = os.path.basename(xmlfile)  # 判断有XML文件的话也一起复制过去
        # self.Copy_file(xmlfile, Class4Dir)

        # ------------判断别的文件夹有没有这张照片和标签，有的话就删除--------------------
        for i in range(len(Class_All)):
            if i != 6:
                if os.path.exists(Class_All[i]):
                    self.Delete_file(Class_All[i], jpgbaseName, xmlbaseName)

    def class_5(self,filePath,savedFileName,jpgbaseName,Class_All):
        # -------------图标部分------------
        self.Pic_Label(7)
        # -------------把文件移动到文件夹---------------
        Class5Dir = Class_All[7]
        MK_dir(Class5Dir)  # 创建过杀文件夹
        copy(filePath, Class5Dir)  # 将图像复制过去、
        xmlfile = savedFileName + '.xml'
        xmlbaseName = os.path.basename(xmlfile)  # 判断有XML文件的话也一起复制过去
        # self.Copy_file(xmlfile, Class5Dir)

        # ------------判断别的文件夹有没有这张照片和标签，有的话就删除--------------------
        for i in range(len(Class_All)):
            if i != 7:
                if os.path.exists(Class_All[i]):
                    self.Delete_file(Class_All[i], jpgbaseName, xmlbaseName)

    def class_6(self,filePath,savedFileName,jpgbaseName,Class_All):
        # -------------图标部分------------
        self.Pic_Label(8)
        # -------------把文件移动到文件夹---------------
        Class6Dir = Class_All[8]
        MK_dir(Class6Dir)  # 创建过杀文件夹
        copy(filePath, Class6Dir)  # 将图像复制过去、
        xmlfile = savedFileName + '.xml'
        xmlbaseName = os.path.basename(xmlfile)  # 判断有XML文件的话也一起复制过去
        # self.Copy_file(xmlfile, Class6Dir)

        # ------------判断别的文件夹有没有这张照片和标签，有的话就删除--------------------
        for i in range(len(Class_All)):
            if i != 8:
                if os.path.exists(Class_All[i]):
                    self.Delete_file(Class_All[i], jpgbaseName, xmlbaseName)

    def classImg(self,filePath, savedFileName, jpgbaseName, name_class_dir):
        MK_dir(name_class_dir)
        copy(filePath, name_class_dir)

        # ------------判断别的文件夹有没有这张照片和标签，有的话就删除--------------------
        for i in name_class_dir_list:
            if i != name_class_dir:
                self.Delete_file(i, jpgbaseName, False)


    def escapekill(self,filePath,savedFileName,jpgbaseName,Class_All):
        # -------------图标部分------------
        self.Pic_Label(9)
        # -------------把文件移动到文件夹---------------
        EscapekillDir = Class_All[9]
        MK_dir(EscapekillDir)  # 创建过杀文件夹
        copy(filePath, EscapekillDir)  # 将图像复制过去、
        xmlfile = savedFileName + '.xml'
        xmlbaseName = os.path.basename(xmlfile)  # 判断有XML文件的话也一起复制过去
        # self.Copy_file(xmlfile, EscapekillDir)

        # ------------判断别的文件夹有没有这张照片和标签，有的话就删除--------------------
        for i in range(len(Class_All)):
            if i != 9:
                if os.path.exists(Class_All[i]):
                    self.Delete_file(Class_All[i], jpgbaseName, xmlbaseName)

    def DeleteEveryKill(self,savedFileName,jpgbaseName,Class_All):
        self.Pic_Label(10)
        xmlfile = savedFileName + '.xml'
        xmlbaseName = os.path.basename(xmlfile)
        for i in range(len(Class_All)):
            if os.path.exists(Class_All[i]):
                self.Delete_file(Class_All[i], jpgbaseName, xmlbaseName)

    def UpLoad(self,Class_All,defaultSaveDir,main=None, sub=None):
        self.list_Path.clear()
        for i in Class_All:
            self.UPload_classFile(i,defaultSaveDir)
        self.Ftp.upload(items=self.list_Path, dir_='/platform', main_queue=main, sub_queue=sub)

    def UPload_classFile(self,PoseEscapeDir,defaultSaveDir):
        PoseEscape_list = []
        PoseEscapetxt_list =  []
        if os.path.exists(PoseEscapeDir):
            name = os.path.basename(os.path.splitext(PoseEscapeDir)[0])
            PosetiveEscapexml = PoseEscapeDir + os.sep + name + '.xml'
            PosetiveEscapetxt = PoseEscapeDir + os.sep + name + '.txt'
            wr = txtwr(PosetiveEscapexml)
            wr_txt = txtwr(PosetiveEscapetxt)#
            name_ = os.listdir(PoseEscapeDir)

            for i in name_:
                if i.endswith(('jpg', 'png', 'jpeg', 'bmp')):
                    PoseEscape_list.append(i)
                    for split_ in i:
                        if split_ == '_':
                            PoseEscapetxt_list.append(i.split('_')[0])
                            break
                        elif split_ == '-':
                            PoseEscapetxt_list.append(i.split('-')[0])
                            break
                    continue
                    TextBrowserNews(self.TextBrowser,news="数据准备中......")
                    jpgName = os.path.splitext(i)[0]
                    xmlName = defaultSaveDir + os.sep + jpgName + '.xml'
                    if os.path.exists(xmlName):
                        copy(xmlName, PoseEscapeDir)
            if len(name_) != 0:
                    wr.write(PoseEscape_list)
                    wr_txt.write(PoseEscapetxt_list)
                    self.list_Path.append(PoseEscapeDir)


